<template>
  <div>
    <a-tree-select
      :value="avalue"
      style="width: 100%"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :tree-data="areas"
      placeholder="请选择"
      :load-data="load"
      @select="onAreaChange"
      allowClear
    />
  </div>
</template>
<script>
import { getChildren } from "@/services/area";
export default {
  props: {
    value:{
      type:String,
      default(){
        return []
      }
    },
    ChangeOnSelect: {
      type: Boolean,
      default() {
        return true;
      },
    },
  },
  watch: {
    value(v1, v2) {
      console.log("-----value------", v1, v2);
      this.avalue = v1
      //this.load();
    },
  },
  data() {
    return {
      areas: [
      ],
      avalue:'',

      //valueSelected:[]
    };
  },
  computed: {},
  mounted() {
    this.load();
  },
  methods: {
    async loadItem(_this, current) {
      if (_this.value && _this.value.length > 0) {
        for (let i = 0; i < _this.value.length - 1; i++) {
          current = await _this.getChildren(current, _this.value, i);
        }
        //re();
      }
    },
    getChildren(current, key) {
      let _this = this;
      return new Promise((resolve) => {
        getChildren(key).then((res) => {
          let next = null;
          if (res.data && res.data.result) {
            if (current) {
              let children = res.data.result.map((x) => {
                let item = {
                  label: x.s_name,
                  title: x.s_name,
                  key: x.uid,
                  value: x.uid,
                  isLeaf: x.level === "street",
                  obj: x,
                };

                if (x.uid == key) {
                  next = item;
                }
                return item;
              });
              current.dataRef.children = [...children]
              _this.areas = [..._this.areas]
              //_this.$set(current, "children", children);
              current = next;
            }
          }
          resolve(next);
        });
      });
    },
    load(treeNode) {
      console.log("***************", treeNode);
      const _this = this;
      return new Promise((re, rej) => {
        if (!treeNode) {
          getChildren(0)
            .then((res) => {
              if (res.data && res.data.result) {
                let privence = null;
                if (_this.value && _this.value.length > 0) {
                  privence = _this.value[0];
                }
                let current = null;
                let areas = res.data.result.map((x) => {
                  let item = {
                    label: x.s_name,
                    title: x.s_name,
                    value: x.uid,
                    key: x.uid,
                    isLeaf: x.level === "street",
                    obj: x,
                  };
                  if (x.uid == privence) {
                    current = item;
                  }
                  return item;
                });
                _this.areas = [...areas];
                //_this.loadItem(_this, current, re);
                console.log("-------areas-------", areas);
                re();
              }
            })
            .catch((err) => {
              rej(err);
            });
        }else{
          if(!treeNode.isLeaf && (!treeNode.dataRef.children || treeNode.dataRef.children.length == 0)){
            _this.getChildren(treeNode,treeNode.dataRef.value).then(()=>{
              re()
            }).catch(err=>{
              rej(err)
            })
            return
          }
          re()
        }
      });
    },

    getSelect(selectedOptions) {
      const index = selectedOptions.length - 1;
      if (index < 0) {
        return;
      }
      //const _this = this;
      const targetOption = selectedOptions[index];
      //this.station.area_id = targetOption.uid
      return targetOption;
    },
    loadData(selectedOptions) {
      const targetOption = this.getSelect(selectedOptions);
      if (!targetOption) {
        return;
      }

      if (targetOption.isLeaf) {
        return;
      }
      if (targetOption.children && targetOption.children.length > 0) {
        return;
      }
      const _this = this;
      getChildren(targetOption.value)
        .then((res) => {
          if (res.data && res.data.result) {
            targetOption.children = res.data.result.map((x) => {
              return {
                label: x.s_name,
                title: x.s_name,
                key: x.uid,
                value: x.uid,
                isLeaf: x.level === "street",
                lon: x.lon,
                lat: x.lat,
                obj: x,
              };
            });
            _this.areas = [..._this.areas];
          }
        })
        .finally(() => {
          targetOption.loading = false;
        });

      // load options lazily
    },

    onAreaChange(val,node) {
      /*var obj = undefined
      if(val && val.length > 0){
        obj = this.getSelect(selectedOptions)
      }*/
      this.avalue = val
      console.log("-----------------onarea",val,node.dataRef.obj)
      this.$emit("area-change", val,node.dataRef.obj);
      this.$emit("input", this.avalue);
    },
    filter(inputValue, path) {
      return path.some(
        (option) =>
          option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    },
  },
};
</script>
<style scoped>
</style>
